<template>
  <div>
    <a-modal class="form1"
             v-model="dialogVisible"
             title="公司附件"
             width="400px"
             :dialog-style="{ top: '15vh' }"
             ok-text="确认"
             cancel-text="取消"
             @ok="handleOk()"
             @cancel="cancelOK()">
      <a-form-model ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="labelCol"
                    :wrapper-col="wrapperCol">
        <a-row>
          <a-col :span="24"
                 v-if="fileuploadType === 1">
            <a-form-model-item label="营业执照上传"
                               style=""
                               prop="attachmentId"
                               v-if="imgStatus === 1">
              <img v-if=" form.attachmentId "
                   :src="previewUrl + form.attachmentId"
                   alt="文件丢失，请重新上传" />
              <a-upload v-if=" !form.attachmentId"
                        name="file"
                        list-type="picture-card"
                        class="avatar-uploader"
                        :show-upload-list="false"
                        :action="uploadUrl"
                        :before-upload="beforeUpload"
                        @change="businessLicensePicChange">
                <div>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-model-item>
            <a-form-model-item label="营业执照上传"
                               style=""
                               prop="attachmentId"
                               v-if="imgStatus === 2">
              <a-upload v-if=" form.attachmentId"
                        name="file"
                        list-type="picture-card"
                        class="avatar-uploader"
                        :show-upload-list="false"
                        :action="uploadUrl"
                        :before-upload="beforeUpload"
                        @change="businessLicensePicChange">
                <img v-if="form.attachmentId"
                     :src="previewUrl + form.attachmentId"
                     alt="文件丢失，请重新上传" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">
                    Upload
                  </div>
                </div>
              </a-upload>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24"
                 v-if="fileuploadType === 2">
            <a-form-model-item label="附件上传"
                               style=""
                               prop="attachmentId">
              <a-upload name="file"
                        :multiple="false"
                        :action="uploadUrl"
                        :file-list="fileList"
                        :headers="headers"
                        :remove="removefile"
                        :before-upload="beforeUploadFile"
                        @preview="previewClick"
                        @change="fileChange">
                <a-button :disabled="fileList.length === 1">
                  <a-icon type="upload" /> 附件上传
                </a-button>
              </a-upload>
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="附件类型"
                               style=""
                               prop="attachmentType">
              <a-select v-model="form.attachmentType"
                        placeholder="请选择证件类型"
                        disabled>
                <a-select-option v-for="item in attachmentTypeArry"
                                 :value="item.type"
                                 :key="item.id">
                  {{item.title}}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24">
            <div>
              <a-form-model-item label="附件到期时间"
                                 style=""
                                 prop="expireDate">
                <a-date-picker v-model="form.expireDate"
                               type="date"
                               placeholder="请选择附件到期时间"
                               style="width: 100%;"
                               @change="getDateonChange" />
              </a-form-model-item>
            </div>
          </a-col>
        </a-row>

        <a-row>
          <a-col :span="24">
            <a-form-model-item label="附件描述"
                               prop="description">
              <a-textarea v-model="form.description"
                          placeholder="请输入附件描述"
                          auto-size />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
  </div>
</template>
<script>
import '@/assets/css/form.less'
import moment from 'moment';
import setting from '@/settings.js'
export default {
  name: 'UserEditForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
  },
  data () {
    return {
      headers: {
        authorization: 'authorization-text',
      },
      fileList: [],
      fileList1: [],
      labelCol: { span: 7 },
      wrapperCol: { span: 15 },
      tenantAttachments: '',
      //图片是否上传 1新建 2修改
      imgStatus: 1,
      loading: false,
      expireDate: null,
      // true 新建 false 修改
      clickStatus: true,
      //上传类型 1.图片 2.文件 第一次新建必须是1营业执照 类型营业执照  后面上传是2 文件 类型 其他
      fileuploadType: 1,
      form: {
        //附件ID，文件服务器的文件ID或图片ID
        attachmentId: '',
        //附件类型 1营业执照 2门头照片 3工作间照片 4法人身份证正面 5法人身份证反面 6协议 7其他
        attachmentType: '1',
        //附件类型名称
        attachmentTypeName: '',
        //描述
        description: '',
        //文件到期日，yyyy-MM-dd
        expireDate: '',
        //企业关联附件ID，主键
        tenantAttachmentId: '',
        fileType: '',
        describe: '',
      },
      attachmentTypeArry: [
        {
          title: '营业执照',
          type: '1',
        },
        {
          title: '其他',
          type: '7',
        },
      ],
      // 上传地址
      uploadUrl: setting.uploadUrl,
      // 预览地址
      previewUrl: setting.previewUrl,
      //{ pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: '请输入正确的邮箱' } { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号' }
      rules: {
        attachmentId: [{ required: true, message: '请上传图片' }],
        expireDate: [{ required: true, message: '请选择附件到期时间' }],
      },
      dialogVisible: false
    }
  },
  mounted () {
    console.log(123123)
  },
  methods: {
    moment,
    //获取列表
    tenantAttachment (tenantAttachments) {
      console.log(tenantAttachments, 'tenantAttachments');
      this.tenantAttachments = tenantAttachments
      this.clickStatus = true
      if (tenantAttachments && tenantAttachments.length !== 0) {
        console.log('qita');
        this.fileuploadType = 2
        this.form.attachmentType = '7'
        this.form.attachmentTypeName = '其他'
        console.log(this.form.attachmentType)
      } else {
        this.fileuploadType = 1
        this.form.attachmentType = '1'
        this.form.attachmentTypeName = '营业执照'
      }
    },
    //修改编辑联系人
    getList (item) {
      console.log(item);
      console.log(this.fileList1);
      this.fileList = this.fileList1
      if (item.attachmentType === '1') {
        this.fileuploadType = 1
      } else {
        this.fileuploadType = 2
      }
      this.imgStatus = 2
      this.$set(this, 'form', JSON.parse(JSON.stringify(item)));
      this.clickStatus = false
    },

    //确定新增
    handleOk () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          let form = JSON.parse(JSON.stringify(this.form));
          this.$emit('confirmFileUpload', form);
          this.concel()
        }
      })
    },
    //取消新增 如果form表单没值就是第一次新增 有值就是取消修改取消新增
    cancelOK () {
      this.concel()
      this.$emit('cancel')
    },
    //表单清空
    concel () {
      for (let item in this.form) {
        this.form[item] = null;
      }
      console.log(this.form);
      this.$refs.ruleForm.resetFields();
      this.fileList = []
    },
    //上传图片之前
    beforeUpload (file) {
      console.log(file);
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.$message.error('请上传JPG或者PNG格式的图片');
      }
      return isJpgOrPng;
    },
    // 营业执照和文件上传
    businessLicensePicChange (val) {
      this.loading = true
      if (val.file.status === 'done') {
        this.form.attachmentId = val.file.response.result;
        // 如果上传成功图片则识别营业执照
        console.log(val);
        if (val.fileList.length > 1) {
          if (val.fileList[val.fileList.length - 2].response.result !== this.form.attachmentId) {
            let formDate = new FormData()
            formDate.append('attachmentId', val.fileList[val.fileList.length - 2].response.result)
            this.$store.dispatch('request', this.$api.register.getdeletFile(formDate)).then(res => {

            })
            console.log('前一个要删掉');
          }
        }
        console.log(this.form.attachmentId);
        this.form.describe = val.file.name
        this.form.fileType = val.fileList[0].name.split('.')[1]
        this.loading = false
      }
    },
    //上传文件前
    beforeUploadFile (file, fileList) {
      //如果有types中的文件类型 为false 没有为true需要提示
      var isAllow = false
      let types = ['.docx', '.doc', '.xls', '.xlxs', '.jpg', '.png', '.jpeg']
      let extension = /\.[^\.]+/.exec(file.name);
      for (var i = 0; i < types.length; i++) {
        console.log(extension[0]);
        console.log(types[i].indexOf(extension[0]), 'types[i].indexOf(extension[0])');
        if (types[i].indexOf(extension[0]) !== -1) {
          isAllow = true
        }
      }
      if (!isAllow) {
        this.$message.error('请上传jpg, jpeg, png, doc, docx, xls, xlxs格式的文件');
        this.fileList = []
      } else {
        this.fileList = fileList

      }

      this.fileList1 = fileList
      return isAllow;
    },
    fileChange (val) {
      console.log(val);
      if (val.file.status === 'done') {
        console.log(val);
        this.form.attachmentId = val.file.response.result;
        this.form.describe = val.fileList[0].name
        this.form.fileType = val.fileList[0].name.split('.')[1]
        // 如果上传成功图片则识别营业执照
      }
    },
    previewClick (file) {
      console.log(file, 'previewClick');
    },
    //移除文件的回调
    removefile () {
      this.fileList = []
      this.form.attachmentId = ''
      // let formDate = new FormData()
      // formDate.append('attachmentId', file.response.result)
      // this.$store.dispatch('request', this.$api.register.getdeletFile(formDate)).then(res => {
      //   console.log(res);
      //   this.fileList = []
      //   this.form.attachmentId = ''
      // })
    },

    //时间选择
    getDateonChange (e) {
      // this.form.expireDate = e
      // this.form.expireDate = moment(this.form.expireDate, 'YYYY-MM-DD')
      this.form.expireDate = e._d.format('yyyy-MM-dd');
    },
  },
  watch: {
    visible (newVal) {
      this.dialogVisible = newVal;
    }
  }
}
</script>
<style lang="less" scoped>
.drawerForm {
  padding: 20px 20px 80px 30px;
  overflow: hidden;
}
/deep/ .ant-form-explain {
  position: absolute;
}
/deep/ .ant-form-item-label > label {
  color: @colorGreyFont;
  font-size: 12px;
  font-family: PingFangSC, PingFangSC-Regular;
}
/deep/ .ant-form label {
  font-size: 12px;
  color: @colorGreyFont;
}
/deep/ .ant-input {
  color: @colorCommonFont;
}
/deep/ .ant-input::placeholder {
  color: #ccc;
}
/deep/ .ant-form-item {
  font-size: 12px;
}
.fileExpiretime {
  position: absolute;
  left: -30px;
}
/deep/ .filedq .ant-col-5 {
  width: 33%;
}
/deep/ .filedq .ant-input {
  margin-left: 10px;
}
/deep/ .filedq1 .ant-col-5 {
  width: 22%;
}
/deep/ .filedq1 .ant-input {
  margin-left: 5px;
}
/deep/.ant-upload.ant-upload-select-picture-card {
  width: 140px;
  height: 80px;
}
/deep/ img {
  width: 138px;
  height: 70px;
}
</style>
